package com.jt.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


import java.io.FileWriter;

/**
 * 使用AOP记录每次方法的执行路径
 * 以及执行时长
 */
@Component
@Aspect
public class ExecutionTimeAop {

    @Pointcut("bean(*ServiceImpl)")
    public void PointCut(){}

    @Around("PointCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        Object result = null;
        try {
            long startTime = System.currentTimeMillis();
            result= joinPoint.proceed();
            Long endTime = System.currentTimeMillis();
            String className =  joinPoint.getSignature().getDeclaringTypeName();     //获取类路径
            String methodName = "执行的方法类全名：" + className + "." + joinPoint.getSignature().getName();                 //获取方法名
            String time = ("方法执行耗时："+ (endTime-startTime) + "ms");
            FileWriter fw = new FileWriter("E:/Log/Log.txt",true);
            fw.append(methodName);fw.append("\r");
            fw.append(time);fw.append("\r");
            fw.flush();fw.close();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new RuntimeException(throwable);
        }
        return result;
    }
}
